package com.lzj.demo.common;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author kaikaiking
 * mybatis-plus的自动填充功能
 * 用于自动填充实体类属性：创建时间、更新时间、创建人账号、修改人账号
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        if(metaObject.hasGetter("createTime")){
            this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        }
        if(metaObject.hasGetter("createBy")){
            this.strictInsertFill(metaObject, "createBy", String.class, "kaikaiking");
        }
        // 或者
        //this.strictInsertFill(metaObject, "createTime", LocalDateTime::now, LocalDateTime.class); // 起始版本 3.3.3(推荐)
        // 或者
        //this.fillStrategy(metaObject, "createTime", LocalDateTime.now()); // 也可以使用(3.3.0 该方法有bug)

        if(metaObject.hasGetter("modifyTime")){
            this.strictInsertFill(metaObject, "modifyTime", LocalDateTime.class, LocalDateTime.now());
        }
        if(metaObject.hasGetter("modifyBy")){
            this.strictInsertFill(metaObject, "modifyBy", String.class, "kaikaiking");
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        if(metaObject.hasGetter("modifyTime")){
            this.strictUpdateFill(metaObject, "modifyTime", LocalDateTime.class, LocalDateTime.now()); // 起始版本 3.3.0(推荐)
        }
        if(metaObject.hasGetter("modifyBy")){
            this.strictUpdateFill(metaObject, "modifyBy", String.class, "kaikaiking"); // 起始版本 3.3.0(推荐)
        }
        // 或者
        //this.strictUpdateFill(metaObject, "updateTime", () -> LocalDateTime.now(), LocalDateTime.class); // 起始版本 3.3.3(推荐)
        // 或者
        //this.fillStrategy(metaObject, "updateTime", LocalDateTime.now()); // 也可以使用(3.3.0 该方法有bug)
    }
}
